package containers;

import java.util.concurrent.CopyOnWriteArrayList;
import util.CardValues;
import util.CardValues.Value;
import casino.Casino;
import casino.GameCard;

public class Build extends CardContainer {
	private int value = 0;
	private static final int gap = 30;
	private int aces = 0;
	public CopyOnWriteArrayList<GameCard> valcards = new CopyOnWriteArrayList<GameCard>();

	public Build(Casino n){
		super(n);
	}
	
	public Build(Casino n, int x, int y){
		super(n,null,x,y,CardValues.width,CardValues.height);
	}
	
	public void add(GameCard c){
		valcards.add(c);
		super.add(c);
	}
	
	public void addDuplicate(GameCard c){
		super.add(c);
	}
	
	public CopyOnWriteArrayList<GameCard> flush(){
		CopyOnWriteArrayList<GameCard> temp = new CopyOnWriteArrayList<GameCard>();
		for(GameCard c: cards){
			temp.add(c);
		}
		cards.clear();
		valcards.clear();
		return temp;
	}
	
	@Override
	public void lengthChange() {
		value = 0;
		aces = 0;
		int newHeight = CardValues.height+(cards.size()-1)*gap;
		setBounds(x, y+(height-newHeight)/2, width, newHeight);
		for(int i = 0; i < cards.size(); i++){
			if(!cards.get(i).faceUp){
				cards.get(i).flip();
			}
			cards.get(i).setPosition(x, y+i*gap);
			casino.bringToFront(cards.get(i));
			cards.get(i).accesible = false;
		}
		for(int i = 0; i < valcards.size(); i++){
			value += cards.get(i).value.ordinal()+1;
			if(cards.get(i).value == CardValues.Value.ace){
				aces++;
			}
		}
	}
	
	public String toString(){
		return "["+x+", "+y+", "+width+", "+height+"]";
	}
	
	public boolean validTake(GameCard c){
		int n = c.value.ordinal()+1;
		for(int i = 0; i<=aces; i++){
			if(n == value+13*i){
				return true;
			}
		}
		if(c.value.equals(Value.ace)){
			n = 14;
			for(int i = 0; i<=aces; i++){
				if(n == value+13*i){
					return true;
				}
			}
		}
		return false;
	}
	
	public int value(){
		return value;
	}

	public void setPosition(int xpos, int ypos){
		x = xpos;
		y = ypos;
	}
}
